import { defineComponent, ref, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElButton,
  ElIcon,
  ElSpace,
  ElLink,
  ElMessage,
  ElMessageBox,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { FormValuesType } from './typings'
import type { fnStateEnum } from '~/store/monitor/typings'
import ProSaasTable from '~/components/ProSaasTable'
import AliIcon from '~/components/AliIocn'
import styles from '../../index.module.scss'
import useVuexGetters from '~/hooks/useVuexGetters'
import StrategyOption from './option'

export default defineComponent(function StrategyView() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const switchState = useVuexGetters('switch', ['taskTypeOpt'])
  const state = reactive({
    StrategyOptionVisible: false,
    type: '',
    record: {}
  })
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '任务名称',
      prop: 'taskName',
      fixed: 'left',
      width: 180,
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '任务类型',
      prop: 'taskType',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <>
          {row.taskType === 1 && '周任务'}
          {row.taskType === 2 && '多时段'}
          {row.taskType === 3 && '全天'}
        </>
      )
    },
    {
      label: '有效期',
      prop: 'taskTrem',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <>
          {row.taskTrem === 0 && '长期'}
          {row.taskTrem === 1 && '定期'}
        </>
      )
    },
    {
      label: '启用光控',
      prop: 'isLightCtr',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <>
          {row.isLightCtr === 1 && '是'}
          {row.isLightCtr === 0 && '否'}
        </>
      )
    },
    {
      label: '是否偏移',
      prop: 'isOffset',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <>
          {row.isOffset === 1 && '是'}
          {row.isOffset === 0 && '否'}
        </>
      )
    },
    {
      label: '是否启用',
      prop: 'enabled',
      showOverflowTooltip: true,
      sortable: true,
      render: ({ row }) => (
        <>
          {row.enabled === 1 && '是'}
          {row.enabled === 0 && '否'}
        </>
      )
    },
    {
      label: '修改时间',
      prop: 'updateTime',
      width: 180,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 180,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
            <AliIcon type="icon-bianji" />
            &nbsp; 编辑
          </ElLink>
          <ElLink type="primary" onClick={() => del(row)}>
            <AliIcon type="icon-shanchu" />
            &nbsp; 删除
          </ElLink>
        </ElSpace>
      )
    }
  ]
  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') {
      proSaasTableRef.value!?.toSearch()
    }
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  //  新增、编辑
  const handleChangeOptionsModal = (type: string, record?: FormValuesType) => {
    state.StrategyOptionVisible = !state.StrategyOptionVisible
    state.record = record || {}
    state.type = type
    if (!state.StrategyOptionVisible && type !== 'read') proSaasTableRef.value!?.toSearch()
  }
  //  删除多个
  const delMultiple = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    delAjax(ids, false)
  }
  //  删除
  const del = (row: FormValuesType) => {
    const ids = row.id
    delAjax(ids, true)
  }
  //  删除请求
  const delAjax = (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认删除数据?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('switch/HardwareRemovePost', { ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }

  return () => {
    if (state.StrategyOptionVisible) {
      return (
        <StrategyOption
          type={state.type}
          record={state.record}
          cancel={() => handleChangeOptionsModal('add')}
        />
      )
    }
    return (
      <ElCard>
        <ProSaasTable
          tableId="strategy_view"
          ref={proSaasTableRef}
          columns={columns}
          searchParams={formValues}
          hasSelection
          dispatchType="switch/HardwareListGet"
          searchFormProps={{
            model: formValues
          }}
          headerTitle={
            <>
              <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                <ElIcon>
                  <Plus />
                </ElIcon>
                &nbsp; 新增
              </ElButton>
              <ElButton type="danger" onClick={delMultiple}>
                <AliIcon type="icon-shanchu" />
                &nbsp; 删除
              </ElButton>
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="taskName" prop="taskName" label="">
              <ElInput
                v-model={formValues.taskName}
                placeholder="任务名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="taskType" prop="taskType">
              <ElSelect
                v-model={formValues.taskType}
                filterable
                clearable
                placeholder="所属设施"
                onChange={clearSearchTable}
              >
                {switchState.taskTypeOpt?.value?.map((item: fnStateEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>
          ]}
        />
      </ElCard>
    )
  }
})
